import React, { useState, useEffect, useCallback, useMemo } from 'react';
import type { TableProps } from 'antd';
import { Form, Input, Table, Typography, Switch, Modal, Select, message, Popconfirm, Button, Radio } from 'antd';
import { EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons';
import { getUserListApi, getRoleListApi, updateUserStatusApi, createUserApi, deleteUserApi } from '../../service';
import type { UserListData, UserListItem, RoleListResponse, RoleListItem } from '../../service/type';
import axios from 'axios';
import styles from './UserList.module.scss';

interface DataType {
    key: string;
    avator?: string;
    disabled: boolean;
    username: string;
    password: string;
    lastLogin: string;
    creator: string;
    role?: string[];
}

const App: React.FC = () => {
    const [editingKey, setEditingKey] = useState('');
    const [editModalVisible, setEditModalVisible] = useState(false);
    const [passwordVisible, setPasswordVisible] = useState(false);
    const [confirmPasswordVisible, setConfirmPasswordVisible] = useState(false);
    const [data, setData] = useState<DataType[]>([]);
    const [loading, setLoading] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [roleModalVisible, setRoleModalVisible] = useState(false);
    const [isAdding, setIsAdding] = useState(false);
    const [searchData, setSearchData] = useState<DataType[]>([]);
    const [roleList, setRoleList] = useState<{ name: string; value: string }[]>([]);
    const [roleLoading, setRoleLoading] = useState(false);
    const [mounted, setMounted] = useState(false);

    const statusOptions = [
        { value: 'all', label: '全部' },
        { value: 'enabled', label: '启用' },
        { value: 'disabled', label: '禁用' }
    ];

    // 在组件挂载后创建 Form 实例
    const [searchForm] = Form.useForm();
    const [editForm] = Form.useForm();

    useEffect(() => {
        setMounted(true);
        return () => {
            setMounted(false);
            searchForm.resetFields();
            editForm.resetFields();
        };
    }, []);

    useEffect(() => {
        const fetchAllData = async () => {
            setLoading(true);
            setRoleLoading(true);
            try {
                const [userRes, roleRes] = await Promise.all([
                    getUserListApi(),
                    getRoleListApi()
                ]);

                if (userRes.data.code === 200 && userRes.data.data.list) {
                    const formattedUsers = userRes.data.data.list.map((user: UserListItem) => ({
                        key: user._id,
                        avator: user.avator,
                        disabled: user.status === 0,
                        username: user.username,
                        password: user.password,
                        lastLogin: user.lastOnlineTime? new Date(user.lastOnlineTime).toLocaleString() : '--',
                        creator: user.creator,
                        role: user.role
                    }));
                    setData(formattedUsers);
                    setSearchData(formattedUsers);
                } else {
                    message.error(userRes.data.msg || '获取用户列表失败');
                }

                if (roleRes.data.code === 200 && roleRes.data.data.list) {
                    const formattedRoles = roleRes.data.data.list.map((role: RoleListItem) => ({
                        name: role.name,
                        value: role._id || ''
                    }));
                    setRoleList(formattedRoles);
                } else {
                    message.error(roleRes.data.msg || '获取角色列表失败');
                }
            } catch (error) {
                console.error('获取数据失败:', error);
                message.error('获取数据失败');
            } finally {
                setLoading(false);
                setRoleLoading(false);
            }
        };
        fetchAllData();
    }, []);

    const handleAssignRole = (userId: string) => {
        const currentUser = data.find(user => user.key === userId);
        editForm.setFieldsValue({ role: currentUser?.role || [] });
        setRoleModalVisible(true);
        setEditingKey(userId);
    };

    const editUser = useCallback((record: DataType) => {
        editForm.setFieldsValue({
            username: record.username,
            password: record.password,
            confirmPassword: record.password,
            disabled: record.disabled ? 1 : 0
        });
        setEditingKey(record.key);
        setEditModalVisible(true);
        setIsAdding(false);
    }, [editForm]);

    const addUser = () => {
        editForm.resetFields();
        editForm.setFieldsValue({ disabled: 0 });
        setEditModalVisible(true);
        setIsAdding(true);
        setEditingKey('');
    };

    const cancel = () => {
        setEditingKey('');
        setEditModalVisible(false);
        setIsAdding(false);
        setRoleModalVisible(false);
        editForm.resetFields();
    };

    const handleDelete = async (key: string) => {
        try {
            // 调用删除用户 API
            console.log('正在删除用户，ID:', key);
            const response = await deleteUserApi(key);
            console.log('删除用户响应:', response);
            
            if (response.data.code === 200) {
                // 重新获取用户列表数据
                const userRes = await getUserListApi();
                if (userRes.data.code === 200 && userRes.data.data.list) {
                    const formattedUsers = userRes.data.data.list.map((user: UserListItem) => ({
                        key: user._id,
                        avator: user.avator,
                        disabled: user.status === 0,
                        username: user.username,
                        password: user.password,
                        lastLogin: user.lastOnlineTime? new Date(user.lastOnlineTime).toLocaleString() : '--',
                        creator: user.creator,
                        role: user.role
                    }));
                    setData(formattedUsers);
                    setSearchData(formattedUsers);
                    message.success('删除用户成功');
                } else {
                    message.error(userRes.data.msg || '获取最新用户列表失败');
                }
            } else {
                console.error('删除用户失败，响应:', response.data);
                message.error(response.data.msg || '删除用户失败');
            }
        } catch (error: any) {
            console.error('删除用户失败:', error);
            if (error.response) {
                console.error('错误响应:', error.response.data);
                message.error(error.response.data.msg || '删除用户失败');
            } else {
                message.error('删除用户失败，请检查网络连接');
            }
        }
    };

    const handleSave = async (isAdding: boolean) => {
        try {
            const values = await editForm.validateFields();
            let newData;
            if (isAdding) {
                try {
                    // 调用创建用户 API
                    const response = await createUserApi({
                        username: values.username,
                        password: values.password,
                        status: values.disabled === 1 ? 0 : 1
                    });
                    
                    if (response.data.code === 200) {
                        // 重新获取用户列表数据
                        const userRes = await getUserListApi();
                        if (userRes.data.code === 200 && userRes.data.data.list) {
                            const formattedUsers = userRes.data.data.list.map((user: UserListItem) => ({
                                key: user._id,
                                avator: user.avator,
                                disabled: user.status === 0,
                                username: user.username,
                                password: user.password,
                                lastLogin: user.lastOnlineTime? new Date(user.lastOnlineTime).toLocaleString() : '--',
                                creator: user.creator,
                                role: user.role
                            }));
                            setData(formattedUsers);
                            setSearchData(formattedUsers);
                            message.success('添加用户成功');
                        } else {
                            message.error(userRes.data.msg || '获取最新用户列表失败');
                        }
                    } else {
                        message.error(response.data.msg || '添加用户失败');
                    }
                } catch (error) {
                    console.error('添加用户失败:', error);
                    message.error('添加用户失败');
                }
            } else {
                // 更新用户信息
                try {
                    // 调用更新用户API
                    const response = await axios.post('/user/update', {
                        userId: editingKey,
                        username: values.username,
                        password: values.password,
                        status: values.disabled
                    });
                    
                    if (response.data.code === 200) {
                        // 更新本地数据
                        newData = data.map(item =>
                            item.key === editingKey ? { ...item, ...values } : item
                        );
                        setData(newData);
                        setSearchData(newData);
                        message.success('编辑成功');
                    } else {
                        message.error(response.data.msg || '编辑失败');
                    }
                } catch (error) {
                    console.error('编辑用户失败:', error);
                    message.error('编辑用户失败');
                }
            }
            setEditModalVisible(false);
            setRoleModalVisible(false);
            setEditingKey('');
            setIsAdding(false);
        } catch (error) {
            console.error('表单验证失败:', error);
            message.error('表单验证失败，请检查输入');
        }
    };

    const handleRoleAssignSave = () => handleSave(false);
    const handleEditSave = () => handleSave(isAdding);

    const handleSearch = async () => {
        try {
            const { username, status } = await searchForm.validateFields();
            let filteredData = data;
            if (username) {
                filteredData = filteredData.filter(item => item.username.includes(username));
            }
            if (status === 'enabled') {
                filteredData = filteredData.filter(item =>!item.disabled);
            } else if (status === 'disabled') {
                filteredData = filteredData.filter(item => item.disabled);
            }
            setSearchData(filteredData);
        } catch (error) {
            console.log('搜索失败', error);
        }
    };

    const handleReset = () => {
        searchForm.resetFields();
        setSearchData(data);
    };

    // 定义一个通用的状态更新函数
    const handleStatusChange = async (checked: boolean, record: DataType) => {
        const newDisabled = !checked;
        try {
            // 调用后端 API 更新用户状态
            const response = await updateUserStatusApi(record.key, newDisabled ? 0 : 1);
            
            if (response.data.code === 200) {
                // 更新本地状态
                const newData = data.map(item =>
                    item.key === record.key ? { ...item, disabled: newDisabled } : item
                );
                setData(newData);
                setSearchData(newData);
                message.success('状态更新成功');

                // 如果正在编辑该用户，更新表单状态
                if (editingKey === record.key && editModalVisible) {
                    editForm.setFieldsValue({ disabled: newDisabled ? 1 : 0 });
                }
            } else {
                message.error(response.data.msg || '状态更新失败');
                // 如果更新失败，恢复原状态
                const newData = data.map(item =>
                    item.key === record.key ? { ...item, disabled: !newDisabled } : item
                );
                setData(newData);
                setSearchData(newData);
            }
        } catch (error) {
            console.error('更新状态失败:', error);
            message.error('更新状态失败');
            // 如果更新失败，恢复原状态
            const newData = data.map(item =>
                item.key === record.key ? { ...item, disabled: !newDisabled } : item
            );
            setData(newData);
            setSearchData(newData);
        }
    };

    const columns: TableProps<DataType>['columns'] = [
        {
            title: '头像',
            dataIndex: 'avator',
            width: '15%',
            render: (text, record) => (
                <div className={styles.avatarContainer}>
                    {text? (
                        <img
                            src={text}
                            className={styles.avatarImage}
                            onClick={() => setPreviewImage(text)}
                            onError={(e) => (e.target as HTMLImageElement).src = 'https://via.placeholder.com/80'}
                        />
                    ) : (
                        <span className={styles.avatarPlaceholder}>{record.username}</span>
                    )}
                </div>
            )
        },
        {
            title: '状态',
            dataIndex: 'disabled',
            width: '10%',
            render: (disabled, record) => (
                <Switch
                    checked={!disabled}
                    onChange={(checked) => {
                        // 更新本地状态
                        const newDisabled = !checked;
                        const newData = data.map(item =>
                            item.key === record.key ? { ...item, disabled: newDisabled } : item
                        );
                        setData(newData);
                        setSearchData(newData);
                        
                        // 如果正在编辑该用户，更新表单状态
                        if (editingKey === record.key && editModalVisible) {
                            editForm.setFieldsValue({ disabled: newDisabled ? 1 : 0 });
                        }
                    }}
                    loading={loading}
                />
            )
        },
        { title: '用户名', dataIndex: 'username' },
        { title: '密码', dataIndex: 'password', width: '15%' },
        { title: '最近登录', dataIndex: 'lastLogin' },
        { title: '创建人', dataIndex: 'creator', width: '15%' },
        {
            title: '操作',
            dataIndex: 'operation',
            width: '15%',
            render: (_, record) => (
                <div className={styles.tableActionButton}>
                    <Button 
                        className={`${styles.actionButton} ${styles.assignRoleButton}`} 
                        onClick={() => handleAssignRole(record.key)}
                        type="link"
                    >
                        分配角色
                    </Button>
                    <Button 
                        className={`${styles.actionButton} ${styles.editButton}`} 
                        onClick={() => editUser(record)}
                        type="link"
                    >
                        编辑
                    </Button>
                    <Popconfirm title="确定要删除吗？" onConfirm={() => handleDelete(record.key)}>
                        <Button 
                            className={`${styles.actionButton} ${styles.deleteButton}`} 
                            type="link"
                        >
                            删除
                        </Button>
                    </Popconfirm>
                </div>
            )
        }
    ];

    // 渲染搜索表单
    const renderSearchForm = () => {
        if (!mounted) return null;
        return (
            <Form form={searchForm} layout="inline" className={styles.searchForm}>
                <Form.Item name="username" label="用户名">
                    <Input />
                </Form.Item>
                <Form.Item name="status" label="启用状态">
                    <Select style={{ width: 120 }}>
                        {statusOptions.map(option => (
                            <Select.Option key={option.value} value={option.value}>
                                {option.label}
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item>
                    <Button type="primary" onClick={handleSearch}>
                        查询
                    </Button>
                </Form.Item>
                <Form.Item>
                    <Button onClick={handleReset}>
                        重置
                    </Button>
                </Form.Item>
            </Form>
        );
    };

    // 渲染角色分配模态框
    const renderRoleModal = () => {
        if (!mounted) return null;
        return (
            <Modal 
                title="分配角色" 
                open={roleModalVisible} 
                onOk={handleRoleAssignSave} 
                onCancel={cancel}
                destroyOnClose
            >
                <Form form={editForm} preserve={false}>
                    <Form.Item label="角色" name="role" rules={[{ required: true, message: '请选择角色' }]}>
                        <Select
                            mode="multiple"
                            style={{ width: '100%' }}
                            placeholder="请选择角色"
                            loading={roleLoading}
                        >
                            {roleList.map(role => (
                                <Select.Option key={role.name} value={role.name}>
                                    {role.name}
                                </Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                </Form>
            </Modal>
        );
    };

    // 渲染编辑用户模态框
    const renderEditModal = () => {
        if (!mounted) return null;
        return (
            <Modal 
                title={isAdding ? "添加用户" : "编辑用户"} 
                open={editModalVisible} 
                onOk={handleEditSave} 
                onCancel={cancel}
                destroyOnClose
            >
                <Form form={editForm} layout="vertical" preserve={false}>
                    <Form.Item label="账号" name="username" rules={[{ required: true, message: '请输入账号' }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item label="密码" name="password" rules={[{ required: true, message: '请输入密码' }]}>
                        <Input.Password
                            visibilityToggle={{ visible: passwordVisible, onVisibleChange: setPasswordVisible }}
                            iconRender={(visible) => (visible? <EyeOutlined /> : <EyeInvisibleOutlined />)}
                        />
                    </Form.Item>
                    <Form.Item label="确认密码" name="confirmPassword" dependencies={['password']} rules={[({ getFieldValue }) => ({
                        validator: (_, value) => (value && getFieldValue('password')!== value? Promise.reject(new Error('两次输入的密码不一致')) : Promise.resolve())
                    })]}>
                        <Input.Password
                            visibilityToggle={{ visible: confirmPasswordVisible, onVisibleChange: setConfirmPasswordVisible }}
                            iconRender={(visible) => (visible? <EyeOutlined /> : <EyeInvisibleOutlined />)}
                        />
                    </Form.Item>
                    <Form.Item label="状态" name="disabled">
                        <Radio.Group 
                            onChange={(e) => {
                                editForm.setFieldsValue({ disabled: e.target.value });
                            }}
                            value={editForm.getFieldValue('disabled') ? 1 : 0}
                        >
                            <Radio value={0}>启用</Radio>
                            <Radio value={1}>禁用</Radio>
                        </Radio.Group>
                    </Form.Item>
                </Form>
            </Modal>
        );
    };

    if (!mounted) {
        return null;
    }

    return (
        <>
            <Button type="primary" onClick={addUser} className={styles.addUserButton}>
                添加用户
            </Button>
            {renderSearchForm()}
            <Table columns={columns} dataSource={searchData} loading={loading} bordered rowClassName="editable-row" pagination={{ pageSize: 10 }} />
            {previewImage && (
                <div className={styles.previewOverlay} onClick={() => setPreviewImage('')}>
                    <img src={previewImage} className={styles.previewImage} />
                </div>
            )}
            {roleModalVisible && renderRoleModal()}
            {editModalVisible && renderEditModal()}
        </>
    );
};

export default App;